package com.teragadgets.android.comic;

import java.io.IOException;
import java.util.Observable;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.xml.sax.SAXException;

import android.content.Context;

import com.teragadgets.android.comic.datamodel.Comic;
import com.teragadgets.android.comic.datamodel.WebComic;
import com.teragadgets.android.comic.datamodel.WebComicDatabase;
import com.teragadgets.android.comic.feed.ComicFeedParser;

public class ComicModel extends Observable {

	private WebComic webComic;
	private int curComic;
	private Vector<Comic> comics;

	public ComicModel(Context ctx, String webComicID, int comicID) {

		curComic = comicID;

		WebComicDatabase db = WebComicDatabase.open(ctx);
		webComic = db.fetchComic(webComicID);
		db.close();

		loadComics(webComic);
		loadComic(ctx, curComic);

		this.setChanged();
		this.notifyObservers();
	}

	public void reloadCurrentComic(Context ctx) {
		loadComic(ctx, curComic);
	}

	public void loadNextComic(Context ctx) {
		curComic++;
		if (curComic >= comics.size())
			curComic = 0;
		loadComic(ctx, curComic);
	}

	public void loadPreviousComic(Context ctx) {
		curComic--;
		if (curComic < 0)
			curComic = comics.size() - 1;
		loadComic(ctx, curComic);
	}

	private void loadComic(Context ctx, int comicID) {
		this.curComic = comicID;
		webComic.setLastRead(curComic);
		this.setChanged();
		this.notifyObservers(comics.get(curComic));
	}

	private void loadComics(WebComic webComic) {
		ComicFeedParser parser = new ComicFeedParser(webComic.getFeed());
		try {
			comics = parser.getComics();

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void save(Context ctx) {
		WebComicDatabase db = WebComicDatabase.open(ctx);
		db.updateLastRead(webComic.getID(), comics.get(curComic).getNumber());
		db.close();
	}
}
